window.addEvent('domready', function() {
	/*****************************************************
	*					TUNER DIAL
	******************************************************/

	// CONFIG
		// this sets the distance of the knob from the center of the dial (in pixels)
		var radius = 44;
		var out = $('dial_value');
	// END OF CONFIG

	var drag = $('drag_knob');
	var knob = $('knob');
	
	// determine the center of the whole dial, relative to the screen. 
	// This is automatically offseted against the dimensions of the knob
	coords = $('dial').getCoordinates();
	dialX = coords.left + (coords.width - knob.getSize().size.x) / 2;
	dialY = coords.top + (coords.height - knob.getSize().size.y) / 2;
	// center of the dial, relative to the dial, offsetted against the dimensions of the knob
	centerX = (coords.width - knob.getSize().size.x) / 2;
	centerY = (coords.height - knob.getSize().size.y) / 2;
	
	drag.makeDraggable({
		'onDrag': 
			function () { 
				// calculate the angle between the drag and the center of the dial
				dcoords = drag.getCoordinates();
				dx = dcoords.left - dialX
				dy = dcoords.top - dialY
				angle = Math.atan(dy/dx);
				
				// move the real knob
				if (dx >= 0) {
					knob.setStyle('left', radius * Math.cos(angle) + centerX);
					knob.setStyle('top',  radius * Math.sin(angle) + centerY);
					out.setText((angle * 50.0 / Math.PI).round() + 25);
				} else {
					knob.setStyle('left', centerX - radius * Math.cos(angle));
					knob.setStyle('top',  centerY - radius * Math.sin(angle));
					out.setText((angle * 50.0 / Math.PI).round() + 75);
				}	
				
			},
			
		'onComplete' :
			function () {
				// return the drag knob on top of the knob
				drag.setStyles(knob.getStyles('top','left'));
			}
	});
	
	// allow the user to change value by clicking on the dial value in the center - NOT FINISHED!
	out.addEvent('click', function() {
		var val = out.getText();
		
		// if val is empty, this means that the input field is already running. Exit
		if (val == "") return;
		
		out.setHTML("<input value=\"" + val +"\">");
		
		var inputfld = out.getElement("input");
		
		// add actions to this input field
		inputfld.addEvent('keyup', function(e) {
			var event = new Event(e);
			
			if (event.key == 'enter') {
				// save on enter
				out.setHTML(inputfld.getValue());
			} else if (event.key == 'esc') {
				// leave on esc
				out.setHTML(val);
			}
		});
	});
	
});